<template>
  <div v-loading="loading" class="monthPlanAdd">
    <b-table
        ref="table"
        :columns="columns"
        :request="request"
        :filterData="appendExtraInfo"
        bordered
        class="bgFFF"
        :disabled="state === 3"
        :delFunc="delFunc"
        :scroll="{ x: 1300 }"
        :exportConfig="{ use: true,select: '导出选中-物资需求月计划',all: '导出全部-物资需求月计划',customColumns:exportColumns}"
        :is-show-count-bar="false"
    >
      <template slot="prefix" v-if="state !== 3">
        <a-button
            type="primary"
            :loading="addLoading"
            @click="addNewSuppliesItem"
        >
          添加行
        </a-button>
      </template>
      <!-- 导入按钮 -->
      <template slot="suffix" slot-scope="scoped" v-if="state !== 3">

        <ExportExcel
            ref="exportExcel"
            icon="export"
            :file-name="$route.meta.title + '模板.xlsx'"
            :export-list="exportList"
            :loading="loadingExport"
            :beforeDownload="beforeDownload"
            button-text="下载导入模板"
        />
        <!--   v-if="hideBuquBtn()" -->
        <ExcelImportButton
            ref="excelImportButton"
            :loading="loadingImport"
            @handleSubmit="confirmImportAction"
            icon="import"
            button-text="批量导入"

        />
      </template>

      <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
      <template
          v-for="col in ['materialName','materialModel','materialUnit','planNum', 'planIntoDate', 'useSite', 'remarks']"
          :slot="col"
          slot-scope="text, record"
      >
        <div :key="col" class="form-item">
          <template v-if="state !== 3">
            <a-date-picker
                v-if="col === 'planIntoDate'"
                v-model="record.planIntoDate"
                value-format="YYYY-MM-DD"
                @change="save(record)"
            />
            <BaseInputNumber
                v-else-if="col === 'planNum'"
                v-model="record[col]"
                :precision="3"
                @blur="save(record)"
            />
            <BaseInput
                v-else
                style="margin: -5px 0"
                :class="col === 'remarks' ? 'remark' : ''"
                v-model="record[col]"
                @blur="save(record)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
    </b-table>
    <ExportResult :visible.sync="visibleExport" :exportList="exportList" width="80%"/>

  </div>
</template>
<script>
import {
  monthPlanDetailList,
  monthPlanDetailAdd,
  monthPlanDetailListDel,
  monthPlanDetailEdit,
  monthPlanDetailAddRow
} from '@/api/project/suppliesMonthPlan/monthPlan.js'
import {materialColumns, exportColumns} from './insideModel'

import {guid} from '@/utils/snow-flake'
import ExportExcel from '@/components/exportExcel/ExportExcel' // 导出
import ExportResult from '@/components/Dialog/ExportResult' // 弹窗
import ExcelImportButton from '@/components/ExcelImportButton' // 批量导入


const data = []

export default {
  name: 'a' + Date.now(),
  props: {
    state: {
      type: Number
    },
    row: {
      type: Object
    }
  },
  data() {
    this.cacheData = data.map((item) => ({...item}))
    return {
      delFunc: monthPlanDetailListDel,
      loading: false,
      addLoading: false,
      queryParam: {},
      columns: materialColumns,
      exportColumns: exportColumns,

      visibleExport: false, // 导入结果弹窗控件
      exportList: [{columns: [], datas: []}], // 导入配置项
      fileList: [], // 当前文件列表
      loadingImport: false, // 导入loading
      loadingExport: false, // 导出loading
      importCheck: {
        物资名称: 'materialName',
        规格型号: 'materialModel',
        计量单位: 'materialUnit',
        计划数量: 'planNum',
        计划进场日期: 'planIntoDate',
        使用部位: 'useSite',
        备注: 'remarks'
      }, // 导入字段对应

      data: this.tableData,
      rules: {
        materialName: [{rule: 'required', message: '物资名称不能为空'}],
        materialModel: [{rule: 'required', message: '规格型号不能为空'}],
        materialUnit: [{rule: 'required', message: '计量单位不能为空'}],
        planNum: [{rule: 'required', message: '计划数量不能为空'}],
        planIntoDate: {rule: 'required', message: '计划进场日期不能为空'},
        useSite: {rule: 'required', message: '使用部位不能为空'}
      },
      request: q => {
        return monthPlanDetailList(Object.assign({}, q, {materialMonthId: this.row.id}))
      },

      //导出的时候需要将第一步的信息也全部导出,这里来追加
      appendExtraInfo: q => {
        q.forEach((item, index)=>{
              item.index = index+1
              item.projectName = this.row.projectName
              item.createTime = this.row.createTime
              item.createPerson = this.row.creatorName
              item.planTime = this.row.planTime
              item.contractPhone = this.row.phone
              item.contractPerson = this.row.accountName
              item.planNo = this.row.codeAll
            }
        )
        return q
      },
    }
  },
  mounted: function () {
    if (this.state === 3) {
      this.editingKey = true
    }
  },
  components: {
    ExcelImportButton,
    ExportResult,
    ExportExcel
  },
  methods: {
    async createList(data) {
      let params = []
      data.forEach((item) => {
        params.push({
          editId: this.row.id,
          // materialCode: item.code,
          // materialId: item.id
          materialModel: item.materialModel,
          materialName: item.materialName,
          materialUnit: item.materialUnit,
          planIntoDate: item.planIntoDate,
          planNum: item.planNum,
          remarks: item.remarks,
          useSite: item.useSite,
        })
      })
      return monthPlanDetailAdd(params)
    },
    //添加行
    addNewSuppliesItem() {
      this.addLoading = true
      let toAdd = {
        editId: this.row.id,
        id: guid(),
        materialModel: '',
        materialName: '',
        materialUnit: '',
        planIntoDate: '',
        planNum: '',
        remarks: '',
        useSite: '',
      }
      monthPlanDetailAddRow(toAdd).then((res) => {
        this.addLoading = false
        if (res.code === 200) {
          //this.initTable()
          this.$refs.table.tableData.push(toAdd)
        }
      })
    },
    initTable() {
      this.pageNo = 1
      this.list()
    },
    list() {
      this.$refs.table.refresh()
    },

    async save(row) {
      await monthPlanDetailEdit(row)
    },

    /**
     * @description: 导出模板前的回调处理
     * @param {Promise} callback：导出方法
     */
    async beforeDownload() {
      let columnsExport = this.$clone(this.columns)
      // 设置默认导出配置项
      this.exportList = [
        {
          columns: columnsExport,
          datas: [{}]
        }
      ]
    },
    /**
     * @description: 批量导入
     * @param {Array} data：导入列表
     */
    async handleImport(e) {
      let form = []

      // 遍历校验表格字段，且添加表单
      for (let index in e) {
        form.push({})
        let keys = e[index]
        let listItem = form[index]
        // 校验excel的表头字段
        for (let i in this.importCheck) {
          let item = this.importCheck[i]
          if (!Object.keys(keys).includes(i) && item !== 'remarks') {
            this.$message.warning(`第${Number(index) + 1}行${i}不能为空`)
            return
          } else {
            try {
              // 类别格式化
              if (item === 'planIntoDate') {
                listItem[item] = this.$dateFormat(keys[i].setDate(keys[i].getDate()), 'D')
              } else {
                listItem[item] = keys[i]
              }
            } catch (error) {
              console.log(error)
              this.$message.warning(`第${Number(index) + 1}行${i}格式有误`)
              return
            }
          }
        }
      }
      // 开始导入
      this.loadingImport = true
      const importRes = await this.createList(form).catch(() => {
        this.loadingImport = false
      })
      this.loadingImport = false
      // 导入成功
      if (importRes.code === 200) {
        if (importRes.data?.length > 0) {
          // 配置导出项，且打开导出结果
          let columnsExport = this.$clone(this.columns)?.filter((i) => i.header !== '操作' && !i.isHidden)
          // 表头添加失败原因
          columnsExport.push({
            dataIndex: 'failureReason',
            ellipsis: true,
            title: '失败原因'
          })

          this.exportList = [
            {
              successCount: importRes.data?.length,
              columns: columnsExport,
              datas: []
            }
          ]
          this.visibleExport = true
          // 如果有导入成功条数，则刷新表格
          importRes.data?.length > 0 && this.initTable()
        } else {
          this.$message.warn('批量导入失败')
        }
      }
    },

    //覆盖导入确认操作
    async confirmImportAction(e) {
      this.loadingImport=true
      let result = await monthPlanDetailList({materialMonthId: this.row.id,pageNo:1,pageSize:1,queryType:"1"}).catch(() => {
        this.loadingImport = false
      })
      this.loadingImport = false
      if (result.code === 200) {
        if (result.data?.length === 0) {
          await this.handleImport(e)
        } else {
          this.$confirm({
            title: '批量导入会覆盖已有数据,继续导入吗?',
            okText: '是',
            okType: 'danger',
            cancelText: '否',
            onOk: ()=>{
              this.handleImport(e)
            }
          })
        }
      } else {
        this.$message.warn('导入失败,请稍后重试')
      }
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number-input,
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }

  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
</style>
